<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备编码" prop="deviceId">
        <el-select
          v-model="queryParams.deviceId"
          placeholder="请选择设备"
          clearable
          filterable
          style="width: 180px"
        >
          <el-option
            v-for="item in deviceOptions"
            :key="item.deviceId"
            :label="`${item.deviceCode} - ${item.deviceName}`"
            :value="item.deviceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="newStatus">
        <el-select
          v-model="queryParams.newStatus"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="在线" value="online" />
          <el-option label="离线" value="offline" />
          <el-option label="维护中" value="maintenance" />
          <el-option label="故障" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态变更" prop="changeReason">
        <el-input
          v-model="queryParams.changeReason"
          placeholder="请输入变更原因"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="记录时间" prop="recordDateRange">
        <el-date-picker
          v-model="queryParams.recordDateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 360px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:deviceStatusLog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:deviceStatusLog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:deviceStatusLog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:deviceStatusLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="deviceStatusLogList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="logId" width="80" />
      <el-table-column label="设备信息" align="center" prop="deviceId" width="160">
        <template slot-scope="scope">
          <div>
            <div style="font-weight: 500; color: #409EFF;">{{ getDeviceCode(scope.row.deviceId) }}</div>
            <div style="font-size: 12px; color: #909399;">{{ getDeviceName(scope.row.deviceId) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态变更" align="center" width="140">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-tag :type="getStatusTagType(scope.row.oldStatus)" size="mini" style="margin-right: 5px;">
              {{ getStatusLabel(scope.row.oldStatus) }}
            </el-tag>
            <i class="el-icon-right" style="margin: 0 5px; color: #909399;"></i>
            <el-tag :type="getStatusTagType(scope.row.newStatus)" size="mini">
              {{ getStatusLabel(scope.row.newStatus) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="系统状态" align="center" width="200">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: space-around; align-items: center;">
            <div style="text-align: center;">
              <div style="font-size: 11px; color: #909399;">信号</div>
              <el-progress 
                type="circle" 
                :percentage="scope.row.signalStrength || 0" 
                :width="30"
                :stroke-width="4"
                :color="getSignalColor(scope.row.signalStrength)"
              />
            </div>
            <div style="text-align: center;">
              <div style="font-size: 11px; color: #909399;">CPU</div>
              <div style="font-size: 12px; font-weight: 500;">
                {{ scope.row.cpuUsage ? parseFloat(scope.row.cpuUsage).toFixed(1) + '%' : '-' }}
              </div>
            </div>
            <div style="text-align: center;">
              <div style="font-size: 11px; color: #909399;">内存</div>
              <div style="font-size: 12px; font-weight: 500;">
                {{ scope.row.memoryUsage ? parseFloat(scope.row.memoryUsage).toFixed(1) + '%' : '-' }}
              </div>
            </div>
            <div style="text-align: center;">
              <div style="font-size: 11px; color: #909399;">温度</div>
              <div style="font-size: 12px; font-weight: 500;" :style="{ color: getTemperatureColor(scope.row.temperature) }">
                {{ scope.row.temperature ? parseFloat(scope.row.temperature).toFixed(1) + '°C' : '-' }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="变更原因" align="left" prop="changeReason" min-width="150" show-overflow-tooltip />
      <el-table-column label="错误信息" align="left" prop="errorMsg" min-width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.errorMsg" style="color: #F56C6C;">{{ scope.row.errorMsg }}</span>
          <span v-else style="color: #67C23A;">正常</span>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" align="center" prop="recordTime" width="140">
        <template slot-scope="scope">
          <div>
            <div style="font-size: 12px;">{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</div>
            <div style="font-size: 11px; color: #909399;">{{ parseTime(scope.row.recordTime, '{h}:{i}:{s}') }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:deviceStatusLog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:deviceStatusLog:remove']"
            style="color: #F56C6C"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备状态记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="关联设备" prop="deviceId">
                  <el-select v-model="form.deviceId" placeholder="请选择设备" filterable style="width: 100%">
                    <el-option
                      v-for="item in deviceOptions"
                      :key="item.deviceId"
                      :label="`${item.deviceCode} - ${item.deviceName}`"
                      :value="item.deviceId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录时间" prop="recordTime">
                  <el-date-picker 
                    v-model="form.recordTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择记录时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="原状态" prop="oldStatus">
                  <el-select v-model="form.oldStatus" placeholder="请选择原状态" style="width: 100%">
                    <el-option label="在线" value="online">
                      <span style="color: #67C23A">在线</span>
                    </el-option>
                    <el-option label="离线" value="offline">
                      <span style="color: #909399">离线</span>
                    </el-option>
                    <el-option label="维护中" value="maintenance">
                      <span style="color: #E6A23C">维护中</span>
                    </el-option>
                    <el-option label="故障" value="error">
                      <span style="color: #F56C6C">故障</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="新状态" prop="newStatus">
                  <el-select v-model="form.newStatus" placeholder="请选择新状态" style="width: 100%">
                    <el-option label="在线" value="online">
                      <span style="color: #67C23A">在线</span>
                    </el-option>
                    <el-option label="离线" value="offline">
                      <span style="color: #909399">离线</span>
                    </el-option>
                    <el-option label="维护中" value="maintenance">
                      <span style="color: #E6A23C">维护中</span>
                    </el-option>
                    <el-option label="故障" value="error">
                      <span style="color: #F56C6C">故障</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="变更原因" prop="changeReason">
                  <el-input 
                    v-model="form.changeReason" 
                    placeholder="请输入状态变更原因"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="系统监控" name="monitor">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="信号强度">
                  <el-slider
                    v-model="form.signalStrength"
                    :min="0"
                    :max="100"
                    show-input
                    :show-input-controls="false"
                    style="margin-right: 20px"
                  >
                  </el-slider>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备温度">
                  <el-input-number
                    v-model="form.temperature"
                    :min="0"
                    :max="100"
                    :precision="1"
                    placeholder="温度"
                    style="width: 100%"
                  >
                    <template slot="append">°C</template>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="CPU使用率">
                  <el-input-number
                    v-model="form.cpuUsage"
                    :min="0"
                    :max="100"
                    :precision="2"
                    placeholder="CPU使用率"
                    style="width: 100%"
                  >
                    <template slot="append">%</template>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="内存使用率">
                  <el-input-number
                    v-model="form.memoryUsage"
                    :min="0"
                    :max="100"
                    :precision="2"
                    placeholder="内存使用率"
                    style="width: 100%"
                  >
                    <template slot="append">%</template>
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="监控预览">
                  <el-card shadow="never" style="border: 1px dashed #dcdfe6;">
                    <div style="display: flex; justify-content: space-around; align-items: center; padding: 20px 0;">
                      <div style="text-align: center;">
                        <div style="margin-bottom: 10px; color: #909399;">信号强度</div>
                        <el-progress 
                          type="circle" 
                          :percentage="form.signalStrength || 0" 
                          :width="60"
                          :color="getSignalColor(form.signalStrength)"
                        />
                      </div>
                      <div style="text-align: center;">
                        <div style="margin-bottom: 10px; color: #909399;">CPU使用率</div>
                        <div style="font-size: 24px; font-weight: bold;" :style="{ color: getUsageColor(form.cpuUsage) }">
                          {{ form.cpuUsage ? parseFloat(form.cpuUsage).toFixed(1) + '%' : '0%' }}
                        </div>
                      </div>
                      <div style="text-align: center;">
                        <div style="margin-bottom: 10px; color: #909399;">内存使用率</div>
                        <div style="font-size: 24px; font-weight: bold;" :style="{ color: getUsageColor(form.memoryUsage) }">
                          {{ form.memoryUsage ? parseFloat(form.memoryUsage).toFixed(1) + '%' : '0%' }}
                        </div>
                      </div>
                      <div style="text-align: center;">
                        <div style="margin-bottom: 10px; color: #909399;">设备温度</div>
                        <div style="font-size: 24px; font-weight: bold;" :style="{ color: getTemperatureColor(form.temperature) }">
                          {{ form.temperature ? parseFloat(form.temperature).toFixed(1) + '°C' : '0°C' }}
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="错误信息" name="error">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="错误信息" prop="errorMsg">
                  <el-input 
                    v-model="form.errorMsg" 
                    type="textarea" 
                    placeholder="请输入错误信息，如果设备正常请留空"
                    :rows="6"
                    maxlength="1000"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-alert
                  title="提示"
                  type="info"
                  description="错误信息用于记录设备状态变更时的具体错误原因，如果设备状态正常可以留空。"
                  :closable="false"
                  show-icon>
                </el-alert>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceStatusLog, getDeviceStatusLog, delDeviceStatusLog, addDeviceStatusLog, updateDeviceStatusLog } from "@/api/system/deviceStatusLog";

export default {
  name: "DeviceStatusLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备状态记录表格数据
      deviceStatusLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前活跃标签
      activeTab: "basic",
      // 设备选项
      deviceOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        newStatus: null,
        changeReason: null,
        recordDateRange: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "关联设备不能为空", trigger: "change" }
        ],
        newStatus: [
          { required: true, message: "新状态不能为空", trigger: "change" }
        ],
        recordTime: [
          { required: true, message: "记录时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeviceOptions();
  },
  methods: {
    /** 查询设备状态记录列表 */
    getList() {
      this.loading = true;
      // 处理日期范围查询
      if (this.queryParams.recordDateRange && this.queryParams.recordDateRange.length === 2) {
        this.queryParams.recordTimeStart = this.queryParams.recordDateRange[0];
        this.queryParams.recordTimeEnd = this.queryParams.recordDateRange[1];
      } else {
        this.queryParams.recordTimeStart = null;
        this.queryParams.recordTimeEnd = null;
      }
      
      listDeviceStatusLog(this.queryParams).then(response => {
        this.deviceStatusLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取设备选项 */
    getDeviceOptions() {
      // 这里应该调用设备API，暂时使用mock数据
      this.deviceOptions = [
        { deviceId: 10000, deviceCode: 'CAM-001', deviceName: '1号池塘摄像头' },
        { deviceId: 10001, deviceCode: 'CAM-002', deviceName: '2号池塘摄像头' },
        { deviceId: 10002, deviceCode: 'SENSOR-001', deviceName: '水质传感器A1' },
        { deviceId: 10003, deviceCode: 'FEEDER-001', deviceName: '投料设备B1' },
        { deviceId: 10004, deviceCode: 'AERATOR-001', deviceName: '增氧设备C1' }
      ];
    },
    /** 获取设备编码 */
    getDeviceCode(deviceId) {
      const device = this.deviceOptions.find(item => item.deviceId === deviceId);
      return device ? device.deviceCode : `ID:${deviceId}`;
    },
    /** 获取设备名称 */
    getDeviceName(deviceId) {
      const device = this.deviceOptions.find(item => item.deviceId === deviceId);
      return device ? device.deviceName : '未知设备';
    },
    /** 获取状态标签 */
    getStatusLabel(status) {
      const statusMap = {
        'online': '在线',
        'offline': '离线',
        'maintenance': '维护中',
        'error': '故障'
      };
      return statusMap[status] || status;
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const statusMap = {
        'online': 'success',
        'offline': 'info',
        'maintenance': 'warning',
        'error': 'danger'
      };
      return statusMap[status] || '';
    },
    /** 获取信号强度颜色 */
    getSignalColor(strength) {
      if (strength >= 80) return '#67C23A';
      if (strength >= 60) return '#E6A23C';
      if (strength >= 40) return '#F56C6C';
      return '#909399';
    },
    /** 获取使用率颜色 */
    getUsageColor(usage) {
      if (!usage) return '#909399';
      if (usage >= 80) return '#F56C6C';
      if (usage >= 60) return '#E6A23C';
      return '#67C23A';
    },
    /** 获取温度颜色 */
    getTemperatureColor(temperature) {
      if (!temperature) return '#909399';
      if (temperature >= 60) return '#F56C6C';
      if (temperature >= 45) return '#E6A23C';
      if (temperature >= 25) return '#67C23A';
      return '#409EFF';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        logId: null,
        deviceId: null,
        oldStatus: null,
        newStatus: null,
        signalStrength: 80,
        cpuUsage: 0,
        memoryUsage: 0,
        temperature: 25,
        errorMsg: null,
        changeReason: null,
        recordTime: null
      };
      this.activeTab = "basic";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加状态记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const logId = row.logId || this.ids
      getDeviceStatusLog(logId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改状态记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logId != null) {
            updateDeviceStatusLog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceStatusLog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logIds = row.logId || this.ids;
      const deviceNames = row.deviceId ? this.getDeviceName(row.deviceId) : '选中的状态记录';
      this.$modal.confirm('是否确认删除"' + deviceNames + '"的状态记录？').then(function() {
        return delDeviceStatusLog(logIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/deviceStatusLog/export', {
        ...this.queryParams
      }, `deviceStatusLog_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.common-table {
  margin-top: 10px;
}

.common-table .el-table__header th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-tag {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.el-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-select .el-input__inner {
  cursor: pointer;
}

/* 搜索表单优化 */
.el-form--inline .el-form-item {
  margin-bottom: 10px;
}

/* 表格操作按钮间距 */
.el-table .cell .el-button + .el-button {
  margin-left: 5px;
}

/* 标签页优化 */
.el-tabs--border-card .el-tab-pane {
  padding: 20px;
}

.el-tabs--border-card .el-tabs__content {
  background-color: #fff;
}

/* 数字输入框优化 */
.el-input-number {
  width: 100%;
}

/* 弹窗宽度响应式 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
  }
}

/* 表格列头样式优化 */
.el-table th.is-leaf {
  border-bottom: 1px solid #EBEEF5;
}

/* 状态标签样式优化 */
.el-tag.el-tag--success {
  border-color: #67C23A;
}

.el-tag.el-tag--warning {
  border-color: #E6A23C;
}

.el-tag.el-tag--danger {
  border-color: #F56C6C;
}

.el-tag.el-tag--info {
  border-color: #909399;
}

/* 状态变更显示优化 */
.status-change {
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-change .el-tag {
  margin: 0 3px;
}

/* 系统状态显示优化 */
.system-status {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.system-status .status-item {
  text-align: center;
}

.system-status .status-item .label {
  font-size: 11px;
  color: #909399;
  margin-bottom: 4px;
}

.system-status .status-item .value {
  font-size: 12px;
  font-weight: 500;
}

/* 滑块优化 */
.el-slider {
  margin-bottom: 10px;
}

/* 监控预览卡片样式 */
.monitor-preview {
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.monitor-preview .preview-item {
  text-align: center;
}

.monitor-preview .preview-item .preview-label {
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.monitor-preview .preview-item .preview-value {
  font-size: 24px;
  font-weight: bold;
}

/* 错误信息显示优化 */
.error-display {
  color: #F56C6C;
}

.error-display.normal {
  color: #67C23A;
}

/* 记录时间显示优化 */
.record-time {
  text-align: center;
}

.record-time .date {
  font-size: 12px;
  font-weight: 500;
}

.record-time .time {
  font-size: 11px;
  color: #909399;
}

/* 设备信息显示优化 */
.device-info {
  text-align: center;
}

.device-info .device-code {
  font-weight: 500;
  color: #409EFF;
  margin-bottom: 2px;
}

.device-info .device-name {
  font-size: 12px;
  color: #909399;
}

/* 进度条优化 */
.el-progress--circle {
  margin-bottom: 5px;
}

.el-progress__text {
  font-size: 11px !important;
  color: #606266;
}
</style>
